

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/fluid.png">
  <link rel="icon" href="/blog/images/base.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Airfe">
  <meta name="keywords" content="">
  
    <meta name="description" content="本文将介绍模块化打包工具Webpack的出现原因、基本配置、以及核心工作原理。">
<meta property="og:type" content="article">
<meta property="og:title" content="Webpack原理">
<meta property="og:url" content="https://airfe.gitee.io/blog/2023/04/10/Webpack%EF%BC%88%E4%B8%80%EF%BC%89%E5%8E%9F%E7%90%86/index.html">
<meta property="og:site_name" content="Airfe的博客">
<meta property="og:description" content="本文将介绍模块化打包工具Webpack的出现原因、基本配置、以及核心工作原理。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/Webpack%E5%8E%9F%E7%90%86.png">
<meta property="article:published_time" content="2023-04-10T00:00:00.000Z">
<meta property="article:modified_time" content="2023-04-10T00:00:00.000Z">
<meta property="article:author" content="Airfe">
<meta property="article:tag" content="打包工具">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/Webpack%E5%8E%9F%E7%90%86.png">
  
  
  
    <meta name="referrer" content="no-referrer" />
  
  <title>Webpack原理 - Airfe的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"airfe.gitee.io","root":"/blog/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"699a5d71ac7179b23874a59b0666a6f6","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","app_key":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":false}},"search_path":"/blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?699a5d71ac7179b23874a59b0666a6f6";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/blog/">
      <strong>Airfe</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/blog/images/bg.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Webpack原理"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-04-10 08:00" pubdate>
          2023年04月10日
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          8.7k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          73 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Webpack原理</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="Webpack究竟解决了什么问题？"><a href="#Webpack究竟解决了什么问题？" class="headerlink" title="Webpack究竟解决了什么问题？"></a>Webpack究竟解决了什么问题？</h1><p>前端应用的繁荣发展，项目代码不断膨胀.。为了减少维护成本，提高代码的可复用性，在前端项目中更高效的管理和维护项目中的每一个资源 &#x3D;&#x3D;&gt; 模块化思想&#x3D;&gt;模块化演变&#x3D;&gt;模块化规范&#x3D;&gt;模块化打包工具</p>
<h2 id="模块化演变"><a href="#模块化演变" class="headerlink" title="模块化演变"></a>模块化演变</h2><p>早在模块化标准还没有诞生的时候，前端模块化的雏形有三种形式：</p>
<ul>
<li><p>文件划分</p>
</li>
<li><p>命名空间</p>
</li>
<li><p>IIFE 私有作用域</p>
</li>
</ul>
<p>文件划分：</p>
<p>把应用的状态和逻辑放到不同的 JS 文件中，HTML 中通过不同的 script 标签一一引入。这样的缺点是：</p>
<ol>
<li>模块变量相当于在全局声明和定义，会有变量名冲突的问题。</li>
<li>变量都在全局定义，导致难以调试，我们很难知道某个变量到底属于哪些模块。</li>
<li><strong>无法清晰地管理模块之间的依赖关系和加载顺序。假如 a.js 依赖 b.js，那么 HTML 中的 script 执行顺序需要手动调整，不然可能会产生运行时错误。</strong></li>
</ol>
<p>命名空间和IIFE（立即执行函数）都可以解决文件划分的前两个缺点，但同样的存在第三个缺点，以及代码不优雅等问题。</p>
<p>之后开始出现一些模块化的规范。</p>
<h2 id="模块化规范"><a href="#模块化规范" class="headerlink" title="模块化规范"></a>模块化规范</h2><h3 id="CommonJS"><a href="#CommonJS" class="headerlink" title="CommonJS"></a>CommonJS</h3><p>是<strong>Node.js</strong>中遵循的模块规范，约定</p>
<ul>
<li>一个文件就是一个模块</li>
<li>每个模块都有单独的作用域</li>
<li>通过module.exports 导出成员</li>
<li>通过require函数载入模块</li>
</ul>
<p>CommonJS 定义了一套完整的模块化代码规范，不过仍然存在一些问题：</p>
<ul>
<li>它的模块加载器由 Node.js 提供，依赖了 Node.js 本身的功能实现。如果 CommonJS 模块直接放到浏览器中无法执行。</li>
<li>CommonJS 约定以同步的方式进行模块加载，这种加载机制放到浏览器端，会带来明显的性能问题。它会产生大量同步的模块请求，浏览器要等待响应返回后才能继续解析模块。即，模块请求会造成<strong>浏览器 JS 解析过程的阻塞，导致页面加载速度缓慢</strong>。</li>
</ul>
<p>因此，该规范主要适用于服务端，因为服务端可以直接从硬盘中调用所需要的模块，而这个过程速度是非常快的。</p>
<p><strong>典型代表有：Node.js、微信小程序。</strong></p>
<blockquote>
<p>但是使用webpack以后中可以在浏览器中使用commonjs，因为webpack可以对其进行处理。</p>
</blockquote>
<h3 id="ES-Module"><a href="#ES-Module" class="headerlink" title="ES Module"></a>ES Module</h3><p>在浏览器中使用<code>ES Module</code>模块化规范</p>
<h4 id="导出"><a href="#导出" class="headerlink" title="导出"></a>导出</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 导出变量或方法</span><br><span class="hljs-keyword">export</span> &#123; name,hello,<span class="hljs-title class_">Preson</span> &#125;<br><span class="hljs-comment">// 取别名</span><br><span class="hljs-keyword">export</span> &#123; hello <span class="hljs-keyword">as</span> fooHello &#125;<br><br><span class="hljs-comment">// 默认导出变量、方法，接收可以随便取名</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> name  <span class="hljs-comment">// 导出</span><br><br><span class="hljs-keyword">import</span> abc <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./module.js&#x27;</span>  <span class="hljs-comment">// 导入</span><br></code></pre></td></tr></table></figure>

<h4 id="导入"><a href="#导入" class="headerlink" title="导入"></a>导入</h4><ul>
<li>export导出不是把值复制一份给你，而是把存放值的<strong>地址</strong>给你（拿到的值会受内部值修改的影响），外部只读不可修改。（浅复制）</li>
<li>导入的成员必须要有完整的文件名称，相对路径中的.&#x2F;不能省略，可以使用绝对路径或完整的url（ &#x2F;xx&#x2F;modules.js 或 http:&#x2F;&#x2F; ）</li>
</ul>
<p>完整文件名称</p>
<blockquote>
<p>使用相对路径的话，不能省略.&#x2F;</p>
</blockquote>
 <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 不能省略文件后缀，也不能省略index.js</span><br><span class="hljs-keyword">import</span> &#123; lowercase &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./utils/index.js&#x27;</span><br></code></pre></td></tr></table></figure>

<p>若只需要执行模块，而不提取成员</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123; &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./module.js&#x27;</span><br></code></pre></td></tr></table></figure>

<p>要拿的成员很多可以先放到一个对象里</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> mod <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./module.js&#x27;</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(mod) <span class="hljs-comment">// mod上有模块导出的所有成员</span><br></code></pre></td></tr></table></figure>

<p>如果需要动态加载模块</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span>(<span class="hljs-string">&#x27;./module.js&#x27;</span>).<span class="hljs-title function_">then</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-variable language_">module</span></span>)&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable language_">module</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<h4 id="运行环境兼容性问题"><a href="#运行环境兼容性问题" class="headerlink" title="运行环境兼容性问题"></a>运行环境兼容性问题</h4><p>由于<code>ES Module</code>是2014年提出来的，早期的浏览器不支持这一特性。兼容性问题还是需要考虑</p>
<h2 id="模块化打包工具的出现"><a href="#模块化打包工具的出现" class="headerlink" title="模块化打包工具的出现"></a>模块化打包工具的出现</h2><p>问题：</p>
<ul>
<li>ES Modules模块系统本身存在环境兼容问题</li>
<li>模块化的方式划分出来的模块文件过多，导致浏览器需要频繁发送网络请求，影响应用工作效率</li>
<li>HTML和CSS这些资源文件也会面临需要被模块化的问题</li>
</ul>
<p>需要一些解决方案&#x2F;工具可以让我们在开发应用的过程中继续享受模块化带来的优势，又不必担心模块化对生产环境的影响。</p>
<p>需求：</p>
<ul>
<li><p>具备编译能力，可以将开发阶段编写的包含新特性的代码转化为能够兼容大多数环境的代码   —— 解决环境兼容问题</p>
</li>
<li><p>将散落的模块打包到一起，解决浏览器频繁请求模块文件、发送网络请求的问题                      —— 解决请求频繁问题</p>
</li>
<li><p>支持不同种类的前端资源模块类型（css,png,…）                                                                          —— 解决不同资源文件模块化问题</p>
<blockquote>
<p>前两点gulp也可以实现，但第三点gulp很难实现，所以前端主流打包工具——Webpack</p>
</blockquote>
</li>
</ul>
<h1 id="如何使用Webpack进行模块化打包？"><a href="#如何使用Webpack进行模块化打包？" class="headerlink" title="如何使用Webpack进行模块化打包？"></a>如何使用Webpack进行模块化打包？</h1><p>本质：实现前端整体的模块化开发的一个模块化打包工具。</p>
<p>作为一个模块打包器，<code>webpack</code>具有以下特性</p>
<ul>
<li>模块加载器（<code>Loader</code>）  编译转换有环境兼容问题的代码 ( 比如转换源代码，解决有些浏览器不兼容ES Module)</li>
<li>代码拆分（<code>Code Splitting</code>） 解决打包文件太大、太碎的问题。比如可以把一开始用到的模块打包到一起，其他模块等到需要时再加载，实现<code>渐进式加载</code></li>
<li>资源模块（<code>Asset Module</code>） <code>webpack</code>支持在<code>js</code>以模块化的方式载入任意类型的资源文件,比如<code>css</code>类型文件</li>
</ul>
<h2 id="快速上手"><a href="#快速上手" class="headerlink" title="快速上手"></a>快速上手</h2><p>1.不使用webpack打包工具</p>
<p><code>ES Module</code>的一种载入方式，<code>type=&quot;module&quot;</code>用来区分加载的是一个普通<code>JS</code>脚本还是一个模块</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">&lt;script  <span class="hljs-built_in">type</span>=<span class="hljs-string">&quot;module&quot;</span>  src=<span class="hljs-string">&quot;src/index.js&quot;</span>&gt; &lt;/script&gt;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>对于不支持<code>ES Module</code>的浏览器，直接这样使用就会报错</p>
</blockquote>
<p>2.使用webpack打包工具</p>
<ul>
<li>初始化<ul>
<li>webpack本身是npm的一个工具模块，首先初始化package.json用来管理npm依赖的版本</li>
<li>webpack是Webpack的核心模块，webpack-cli是Webpack的CLI程序，用来在命令行中调用Webpack</li>
</ul>
</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs bash">// 生成package.json<br>npm init --y <br><br>// 安装Webpack的核心模块和cli程序<br>npm i webpack webpack-cli --save-dev<br></code></pre></td></tr></table></figure>

<blockquote>
<p>npx是npm5.2以后新增的一个命令，可以更方便的执行远程模块或者node_modules中的CLI程序</p>
</blockquote>
<ul>
<li>运行</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">npx webpack<br></code></pre></td></tr></table></figure>

<p><code>Webpack</code>默认会自动从<code>src/index.js</code>文件开始打包，然后根据代码中的模块导入操作自动将所有用到的模块打包到一起。</p>
<ul>
<li><code>dist</code></li>
</ul>
<p>打包结果存放在项目根目录下的<code>dist</code>目录下的<code>main.js</code>文件中</p>
<p>&#x3D;&#x3D;3.修改webpack的默认配置&#x3D;&#x3D;</p>
<p><code>entry</code>（入口）:  指示 Webpack 从哪个文件开始打包</p>
<p><code>output</code>（输出）:  指示 Webpack 打包完的文件输出到哪里去，如何命名等</p>
<p><code>loader</code>（加载器）: webpack 本身只能处理 js、json 等资源，其他资源需要借助 loader，Webpack 才能解析</p>
<p><code>plugins</code>（插件）:  扩展 Webpack 的功能</p>
<p><code>mode</code>（模式）: 主要有两种模式，development（开发模式）和  production（生产模式）</p>
<p>格式：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs bash">module.exports = &#123;<br>  // 入口<br>  entry: <span class="hljs-string">&quot;&quot;</span>,<br>  // 输出<br>  output: &#123;&#125;,<br>  // 加载器<br>  module: &#123;<br>    rules: [],<br>  &#125;,<br>  // 插件<br>  plugins: [],<br>  // 模式<br>  mode: <span class="hljs-string">&quot;&quot;</span>,<br>&#125;;<br></code></pre></td></tr></table></figure>

<ul>
<li><p>在项目根目录下添加一个<code>webpack.config.js</code>配置文件</p>
<p>这个文件运行在<code>nodejs</code>环境中，需要按照<code>CommonJS</code>的规范导入模块导出成员，可以直接在这个文件中使用<code>path</code>之类的<code>Node.js</code>内置模块</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// ./webpack.config.js</span><br><span class="hljs-variable language_">module</span>.<span class="hljs-property">export</span> = &#123;<br>    <span class="hljs-attr">entry</span>:<span class="hljs-string">&#x27;./src/main.js&#x27;</span> <span class="hljs-comment">// 注意这里的./不能省略</span><br>    <span class="hljs-attr">output</span>:&#123;<br>        <span class="hljs-attr">filename</span>:<span class="hljs-string">&#x27;bundle.js&#x27;</span>,<br>        <span class="hljs-attr">path</span>:path.<span class="hljs-title function_">join</span>(__dirname,<span class="hljs-string">&#x27;output&#x27;</span>)<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="如何通过Loader实现特殊资源加载？"><a href="#如何通过Loader实现特殊资源加载？" class="headerlink" title="如何通过Loader实现特殊资源加载？"></a>如何通过Loader实现特殊资源加载？</h1><p><strong>Loader</strong> 专注实现 <strong>资源模块的加载</strong>，从而实现整体项目的打包。</p>
<p>webpack内部默认的<code>loader</code>只能处理<code>js</code>模块，如果需要加载其他类型的模块，就需要配置不同的<code>loader</code></p>
<p>以加载<code>css</code>资源模块为例</p>
<ul>
<li><p>通过<code>npm</code>先去安装这个<code>Loader</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bas">npm install css-loader --save-dev<br></code></pre></td></tr></table></figure>
</li>
<li><p>在配置文件添加对应的配置——css-loader   </p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs bash">// ./webpack.config.js<br>module.export = &#123;<br>    entry:<span class="hljs-string">&#x27;./src/main.js&#x27;</span> // 注意这里的./不能省略<br>    output:&#123;<br>        filename:<span class="hljs-string">&#x27;bundle.js&#x27;</span>,<br>	&#125;,<br>	module:&#123;<br>    	rules:[<br>        	<span class="hljs-built_in">test</span>:/\.css$/,   // 正则表达式匹配，根据打包过程中所遇到文件路径匹配是否使用这个loader<br>        	use:<span class="hljs-string">&#x27;css-loader&#x27;</span> //指定具体的loader<br>    	]	<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>安装<code>style-loader</code></p>
<p>由于<code>css-loader</code>只会把<code>css</code>模块加载到<code>JS</code>代码中，但并不会使用这个模块,需要<code>style-loader</code>将<code>css-loader</code>转换后的结果通过<code>style</code>标签的方式追加在页面。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// ./webpack.config.js</span><br><span class="hljs-variable language_">module</span>.<span class="hljs-property">export</span> = &#123;<br>    <span class="hljs-attr">entry</span>:<span class="hljs-string">&#x27;./src/main.js&#x27;</span> <span class="hljs-comment">// 注意这里的./不能省略</span><br>    <span class="hljs-attr">output</span>:&#123;<br>        <span class="hljs-attr">filename</span>:<span class="hljs-string">&#x27;bundle.js&#x27;</span><br>	&#125;,<br>	<span class="hljs-attr">module</span>:&#123;<br>    	<span class="hljs-attr">rules</span>:[<br>        	<span class="hljs-attr">test</span>:<span class="hljs-regexp">/\.css$/</span>,   <span class="hljs-comment">// 正则表达式匹配，根据打包过程中所遇到文件路径匹配是否使用这个loader</span><br>        	<span class="hljs-attr">use</span>:[<br>                <span class="hljs-string">&#x27;style-loader&#x27;</span>, <span class="hljs-comment">// 注意有多个loader时，执行顺序是从数组后面往前</span><br>                <span class="hljs-string">&#x27;css-loader&#x27;</span> <br>        	]<br>    	]	<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
<h1 id="如何利用插件机制横向扩展Webpack的构建能力？"><a href="#如何利用插件机制横向扩展Webpack的构建能力？" class="headerlink" title="如何利用插件机制横向扩展Webpack的构建能力？"></a>如何利用插件机制横向扩展Webpack的构建能力？</h1><p><strong>Plugin</strong> 解决项目中 <strong>除了资源加载以外</strong> 的自动化工作。</p>
<h2 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h2><ul>
<li>实现自动在打包之前清除<code>dist</code>目录（上次的打包结果）</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">npm install clean-webpack-plugin --save-dev<br></code></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs bash">const &#123;CleanWebpackPlugin&#125; = require(<span class="hljs-string">&#x27;clean-webpack-plugin&#x27;</span>)<br><br>module.export = &#123;<br>    entry:<span class="hljs-string">&#x27;./src/main.js&#x27;</span> // 注意这里的./不能省略<br>    output:&#123;<br>        filename:<span class="hljs-string">&#x27;bundle.js&#x27;</span>,<br>	&#125;,<br>	plugins:[<br>    	new CleanWebpackPlugin()<br>	]<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li>自动生成应用所需要的<code>HTML</code>文件</li>
</ul>
<blockquote>
<p>即自动生成一个使用所有打包结果的html文件到dist目录下。自动引入资源文件的方式，可以确保文件路径正确。</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">npm install html-webpack-plugin --save-dev<br></code></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs bash">const &#123;CleanWebpackPlugin&#125; = require(<span class="hljs-string">&#x27;clean-webpack-plugin&#x27;</span>)<br>const HtmlWebpackPlugin = require(<span class="hljs-string">&#x27;html-webpack-plugin&#x27;</span>)<br><br>module.export = &#123;<br>    entry:<span class="hljs-string">&#x27;./src/main.js&#x27;</span> // 注意这里的./不能省略<br>    output:&#123;<br>        filename:<span class="hljs-string">&#x27;bundle.js&#x27;</span>,<br>	&#125;,<br>	plugins:[<br>    	new CleanWebpackPlugin(),<br>    	new HtmlWebpackPlugin(&#123;<br>    		filename:<span class="hljs-string">&#x27;index.html&#x27;</span>  // 生成的dist下html文件名，默认是index.html<br>            title:<span class="hljs-string">&#x27;自定义标题名&#x27;</span>，<br>            template：<span class="hljs-string">&#x27;./src/index.html&#x27;</span> // 自定义html模板动态生成<br>    	&#125;)<br>	]<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li>根据不同环境为代码注入类似API地址这种可能变化的部分</li>
<li>拷贝不需要参与打包的资源文件到输出目录</li>
</ul>
<blockquote>
<p>有一些不需要参与构建的静态文件，最终也需要发布到线上，建议把这类文件统一 放在项目根目录下的public或者static目录中。</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">npm install copy-webpack-plugin --save-dev<br></code></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs bash">const &#123;CleanWebpackPlugin&#125; = require(<span class="hljs-string">&#x27;clean-webpack-plugin&#x27;</span>)<br>const HtmlWebpackPlugin = require(<span class="hljs-string">&#x27;html-webpack-plugin&#x27;</span>)<br>const CopyWebpackPlugin = require(<span class="hljs-string">&#x27;copy-webpack-plugin&#x27;</span>)<br><br>module.export = &#123;<br>    entry:<span class="hljs-string">&#x27;./src/main.js&#x27;</span> // 注意这里的./不能省略<br>    output:&#123;<br>        filename:<span class="hljs-string">&#x27;bundle.js&#x27;</span>,<br>	&#125;,<br>	plugins:[<br>    	new CleanWebpackPlugin(),<br>    	new HtmlWebpackPlugin(&#123;<br>    		filename:<span class="hljs-string">&#x27;index.html&#x27;</span>  // 生成的dist下html文件名，默认是index.html<br>            title:<span class="hljs-string">&#x27;自定义标题名&#x27;</span>，<br>            template：<span class="hljs-string">&#x27;./src/index.html&#x27;</span> // 自定义html模板动态生成<br>    	&#125;),<br>    	new CopyWebpackPlugin([<br>        	<span class="hljs-string">&#x27;pulic&#x27;</span>  // 需要拷贝的目录或者路径<br>    	])<br>	]<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li>压缩Webpack打包完成后输出的文件</li>
<li>自动发布打包结果到服务器实现自动部署</li>
</ul>
<h2 id="插件机制实现原理"><a href="#插件机制实现原理" class="headerlink" title="插件机制实现原理"></a>插件机制实现原理</h2><p>往webpack的生命周期的钩子函数中挂载一些任务函数实现的。</p>
<h1 id="处理-js-兼容性和规范性"><a href="#处理-js-兼容性和规范性" class="headerlink" title="处理 js 兼容性和规范性"></a>处理 js 兼容性和规范性</h1><p>有人可能会问，<code>js </code>资源<code> Webpack</code> 不能已经处理了吗，为什么我们还要处理呢？</p>
<p>原因是 <code>Webpack</code> 对 <code>js </code>处理是有限的，只能编译<code> js</code> 中 ES 模块化语法，不能编译其他具有新特性的<code>js</code>语法。</p>
<p>其次开发中，团队对代码格式是有严格要求的，我们不能由肉眼去检测代码格式，需要使用专业的工具来检测。</p>
<ul>
<li>针对<code> js</code> 兼容性处理，我们使用<code>Babel</code>来完成</li>
<li>针对代码格式，我们使用 <code>Eslint </code>来完成</li>
</ul>
<p>我们先完成<code> Eslint</code>，检测代码格式无误后，在由<code>Babel</code>做代码兼容性处理</p>
<h2 id="Eslint"><a href="#Eslint" class="headerlink" title="Eslint"></a>Eslint</h2><p>用来检测 js 和 jsx 语法的工具，可以配置各项功能。(Plugin)</p>
<p>1.下载包</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">npm i eslint-webpack-plugin eslint -D<br></code></pre></td></tr></table></figure>

<p>2.定义<code>Eslint</code>配置文件<code>.eslintrc.js</code>（位于项目根目录）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = &#123;<br>  <span class="hljs-comment">// 继承 Eslint 规则</span><br>  <span class="hljs-attr">extends</span>: [<span class="hljs-string">&quot;eslint:recommended&quot;</span>],<br>  <span class="hljs-attr">env</span>: &#123;<br>    <span class="hljs-attr">node</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// 启用node中全局变量</span><br>    <span class="hljs-attr">browser</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// 启用浏览器中全局变量</span><br>  &#125;,<br>  <span class="hljs-attr">parserOptions</span>: &#123;<br>    <span class="hljs-attr">ecmaVersion</span>: <span class="hljs-number">6</span>,<br>    <span class="hljs-attr">sourceType</span>: <span class="hljs-string">&quot;module&quot;</span>,<br>  &#125;,<br>  <span class="hljs-attr">rules</span>: &#123;<br>    <span class="hljs-string">&quot;no-var&quot;</span>: <span class="hljs-number">2</span>, <span class="hljs-comment">// 不能使用 var 定义变量</span><br>  &#125;,<br>&#125;;<br></code></pre></td></tr></table></figure>

<p>3.将<code>Eslint</code>配置到webpack中</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">ESLintWebpackPlugin</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">&quot;eslint-webpack-plugin&quot;</span>);<br><br><span class="hljs-variable language_">module</span>.<span class="hljs-property">export</span> = &#123;<br>    <span class="hljs-attr">entry</span>:<span class="hljs-string">&#x27;./src/main.js&#x27;</span>, <span class="hljs-comment">// 注意这里的./不能省略</span><br>    <span class="hljs-attr">output</span>:&#123;<br>        <span class="hljs-attr">filename</span>:<span class="hljs-string">&#x27;bundle.js&#x27;</span>,<br>	&#125;,<br>	<span class="hljs-attr">plugins</span>:[<br>    	<span class="hljs-keyword">new</span> <span class="hljs-title class_">ESLintWebpackPlugin</span>([<br>            <span class="hljs-comment">// 指定检查文件的根目录</span><br>            <span class="hljs-attr">context</span>: path.<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">&quot;src&quot;</span>)<br>    	])<br>	],<br>    <span class="hljs-attr">mode</span>: <span class="hljs-string">&quot;development&quot;</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>4.运行指令，在控制台查看<code>Eslint</code>检查效果</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">npx webpack<br></code></pre></td></tr></table></figure>

<p>5.可以通过配置<code>.eslintignore</code>更精细的控制<code>Eslint</code>检查、不检查的文件</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-comment"># 忽略dist目录下所有文件</span><br>dist<br></code></pre></td></tr></table></figure>

<h2 id="Babel"><a href="#Babel" class="headerlink" title="Babel"></a>Babel</h2><p><code>Babel</code>是目前主流的一款<code>js</code>编译器，可以帮助我们将一些使用了新特性的代码编译为当前环境支持的代码。</p>
<p>Babel是基于插件机制实现的，我们需要一个插件来转换一个代码特性，preset-env相当于一个插件的集合，这个集合包含了最新的js新特性，</p>
<p>1.下载包</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">npm i babel-loader @babel/core @babel/preset-env -D<br></code></pre></td></tr></table></figure>

<p>2.定义<code>Babel</code>配置文件<code>babel.config.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = &#123;<br>  <span class="hljs-comment">// 预设</span><br>  <span class="hljs-attr">presets</span>: [<span class="hljs-string">&quot;@babel/preset-env&quot;</span>]<br>&#125;;<br></code></pre></td></tr></table></figure>

<ul>
<li>presets 预设：就是一组 Babel 插件, 扩展 Babel 功能<ul>
<li><code>@babel/preset-env</code>: 一个智能预设，允许您使用最新的 JavaScript。</li>
<li><code>@babel/preset-react</code>：一个用来编译 React jsx 语法的预设</li>
<li><code>@babel/preset-typescript</code>：一个用来编译 TypeScript 语法的预设</li>
</ul>
</li>
</ul>
<p>3.将<code>Babel </code>配置到<code>webpack</code>中</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">module</span>.<span class="hljs-property">export</span> = &#123;<br>    <span class="hljs-attr">entry</span>:<span class="hljs-string">&#x27;./src/main.js&#x27;</span> <span class="hljs-comment">// 注意这里的./不能省略</span><br>    <span class="hljs-attr">output</span>:&#123;<br>        <span class="hljs-attr">filename</span>:<span class="hljs-string">&#x27;bundle.js&#x27;</span>,<br>	&#125;,<br>	<span class="hljs-attr">module</span>:&#123;<br>    	<span class="hljs-attr">rules</span>:[<br>            <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.js$/</span>,<br>            <span class="hljs-attr">exclude</span>: <span class="hljs-regexp">/node_modules/</span>, <span class="hljs-comment">// 排除node_modules代码不编译</span><br>            <span class="hljs-attr">loader</span>: <span class="hljs-string">&quot;babel-loader&quot;</span><br>    	]	<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="Webpack核心工作原理"><a href="#Webpack核心工作原理" class="headerlink" title="Webpack核心工作原理"></a>Webpack核心工作原理</h1><p><code>Webpack</code>在整个打包的过程中：</p>
<ul>
<li>通过<code>Loader</code>处理特殊类型资源的加载，例如加载样式、图片</li>
<li>通过<code>Plugin</code>各种自动化的构建任务，例如自动压缩、自动发布</li>
</ul>
<p>查阅源码的思路：</p>
<ol>
<li><p><code>Webpack CLI</code>启动打包流程</p>
<blockquote>
<p><code>Webpack CLI</code>：作用就是将<code>CLI</code>参数和<code>Webpack</code>配置文件中的配置整合得到一个完整的配置对象</p>
</blockquote>
<p><code>Webpack CLI</code>会通过<code>yargs</code>模块解析<code>CLI</code>参数(运行<code>webpack</code>命令时通过命令行传入的参数)，调用<code>bin/utils/convert-argv.js</code>模块将得到的命令行参数转换为<code>Webpack</code>的配置选项对象。然后开始载入<code>Webpack</code>核心模块，传入配置选项，创建<code>Compiler</code>对象。</p>
</li>
<li><p>载入<code>Webpack</code>核心模块，创建<code>Compiler</code>对象</p>
<p>根据传入的<code>Option</code>是数组还是对象，决定多路打包还是单线打包。</p>
</li>
<li><p>使用<code>Compiler</code>对象开始编译整个项目</p>
<p>创建了<code>Compiler</code>之后<code>Webpack</code>开始注册已配置的插件，触发特定的<code>Hook</code>,调用<code>Compiler</code>对象的<code>run</code>方法，开始构建整个应用。</p>
</li>
<li><p>从入口文件开始，解析模块依赖,形成依赖关系树</p>
<p>创建<code>compilation</code>作为整个上下文变量，紧接着触发<code>make</code>钩子，进入到整个构建过程中最核心的阶段：<code>make</code>阶段。</p>
</li>
<li><p>递归依赖树，将每个模块交给对应的<code>Loader</code>处理</p>
<p><code>make</code>阶段主体的目标：根据<code>entry</code>配置找到入口模块，开始依次递归出所有依赖，形成依赖关系树，然后将递归到的每个模块交给不同的<code>Loader</code>处理 。 </p>
</li>
<li><p>合并<code>Loader</code>处理完的结果，将打包结果输出到<code>dist</code>目录</p>
</li>
</ol>
<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><p><a target="_blank" rel="noopener" href="https://webpack.docschina.org/concepts/">官方文档</a></p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/" class="category-chain-item">前端技术栈</a>
  
  
    <span>></span>
    
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/%E6%89%93%E5%8C%85%E5%B7%A5%E5%85%B7/" class="category-chain-item">打包工具</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/blog/tags/%E6%89%93%E5%8C%85%E5%B7%A5%E5%85%B7/">#打包工具</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Webpack原理</div>
      <div>https://airfe.gitee.io/blog/2023/04/10/Webpack（一）原理/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Airfe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年4月10日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2023/04/12/HTML5%E7%89%B9%E6%80%A7/" title="HTML5特性">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">HTML5特性</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2023/04/10/Webpack%EF%BC%88%E4%BA%8C%EF%BC%89%E7%94%9F%E4%BA%A7%E7%8E%AF%E5%A2%83%E4%BC%98%E5%8C%96/" title="Webpack生产环境优化">
                        <span class="hidden-mobile">Webpack生产环境优化</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appKey":"P5fzMTGSJIoTaGvmgzsUHeNZ","path":"window.location.pathname","placeholder":"发表你的看法吧~","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false,"appid":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appkey":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com"},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
        <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数</span> <span id="times">载入时分秒</span> <script src="js/duration.js"></script> </div> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量 
        <span id="leancloud-site-pv"></span>
         次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数 
        <span id="leancloud-site-uv"></span>
         人
      </span>
    
    

  
</div>

  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      蜀ICP备2023008943号
    </a>
  </span>
  
    
      <span>
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=https://beian.miit.gov.cn/"
          rel="nofollow noopener"
          class="beian-police"
          target="_blank"
        >
          
            <span style="visibility: hidden; width: 0">|</span>
            <img src="" srcset="/blog/img/loading.gif" lazyload data-original="/blog/img/police_beian.png" alt="police-icon"/>
          
          <span>京公网安备12345678号</span>
        </a>
      </span>
    
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/blog/js/leancloud.js" ></script>

  <script  src="/blog/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>

        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body>
</html>
